package com.liu.car_module;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dequan.bean.DqAuthAPPDevs;
import com.dequan.bean.DqAuthAPPPageBean;
import com.dequan.bean.DqAuthKeys;
import com.dequan.bean.DqAuthKeysPageBean;
import com.dequan.bean.DqGpsInfo;
import com.dequan.bean.DqMcuCommInfo;
import com.dequan.bean.DqVehState;
import com.dequan.ble.commonality.ApiButtUtils;
import com.dequan.network.callback.DqAuthAssistantKeyCallBack;
import com.dequan.network.callback.DqAuthDevsCallBack;
import com.dequan.network.callback.DqAuthKeysCallBack;
import com.dequan.network.callback.DqBindDeviceCallBack;
import com.dequan.network.callback.DqBleStateCallBack;
import com.dequan.network.callback.DqDelAuthKeyCallBack;
import com.dequan.network.callback.DqDeviceGpsCallBack;
import com.dequan.network.callback.DqInitProjectCallBack;
import com.dequan.network.callback.DqVehStateCallBack;
import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;

/**
 * uni-app 插件
 * version: 1.0
 * date: 2020.7.24
 * author: liu
 */

public class JsModule extends WXModule {
    private static Application mApplication;
    private static Activity mActivity;

    public static void init(Application application) {
        mApplication = application;
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {

            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {
                mActivity = activity;
            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }

    public void onSuccess(String message, JSONObject obj, JSCallback jsCallback) {
        JSONObject data = new JSONObject();
        data.put("success", true);
        if (null != message) {
            data.put("message", message);
        }else {
            data.put("message", "");
        }
        if (null != obj) {
            data.put("data", obj);
        }else {
            data.put("data", new JSONObject());
        }
        jsCallback.invoke(data);
    }

    public void onFailure(String message, JSCallback jsCallback) {
        JSONObject data = new JSONObject();
        data.put("success", false);
        data.put("message", message);
        jsCallback.invoke(data);
    }

/**************************** 以下是具体方法 **************************/

    /**
     * 测试方法，异步返回传入的值
     * @param value
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void testMethod(String value, JSCallback jsCallback) {
        jsCallback.invoke(value);
    }

    /**
     * 项目登录完进入主界面初始化
     * @param uid
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqLoginInitProject(String uid, final JSCallback jsCallback) {
        ApiButtUtils.dqLoginInitProject(mApplication, uid, new DqInitProjectCallBack() {
            @Override
            public void dqInitProjectSuccess(String s) {
                if (jsCallback == null) return;
                onSuccess(s, null, jsCallback);
            }

            @Override
            public void dqInitProjectOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }

            @Override
            public void dqInitReadDeviceSuccessInfo(String s) {

            }

            @Override
            public void dqInitReadDeviceErrorInfo(String s) {

            }
        });
    }

    /**
     * APP注册成功用这个初始化方法
     * @param uid
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqRegisterInitProject(String uid, final JSCallback jsCallback) {
        ApiButtUtils.dqRegisterInitProject(mApplication, uid, new DqInitProjectCallBack() {
            @Override
            public void dqInitProjectSuccess(String s) {
                if (jsCallback == null) return;
                onSuccess(s, null, jsCallback);
            }

            @Override
            public void dqInitProjectOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }

            @Override
            public void dqInitReadDeviceSuccessInfo(String s) {

            }

            @Override
            public void dqInitReadDeviceErrorInfo(String s) {

            }
        });
    }

    /**
     * 执行蓝牙封装类和权限申请以及蓝牙状态回调
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void checkBluetoothPermission(final JSCallback jsCallback) {
        ApiButtUtils.checkBluetoothPermission(mActivity, new DqBleStateCallBack() {
            @Override
            public void dqBindDeviceState(String s) {

            }

            @Override
            public void dqBindDeviceSuccess(String s) {
                if (jsCallback == null) return;
                onSuccess(s, null, jsCallback);
            }

            @Override
            public void dqBindDeviceOnError(String s) {
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * 当前设备列表
     * @param params
     * @param jsCallback
     */
    @JSMethod(uiThread = true)
    public void dqAuthDevs(JSONObject params, final JSCallback jsCallback) {
        String pageIndex = params.getString("pageIndex");
        String pageSize = params.getString("pageSize");
        ApiButtUtils.dqAuthDevs(pageIndex, pageSize, new DqAuthDevsCallBack() {
            @Override
            public void dqAuthDevsSuccess(DqAuthAPPDevs dqAuthAPPDevs) {
                if (jsCallback == null) return;
                JSONObject data = new JSONObject();
                data.put("total", dqAuthAPPDevs.getTotal());
                data.put("pageIndex", dqAuthAPPDevs.getPageIndex());
                data.put("pageSize", dqAuthAPPDevs.getPageSize());
                JSONArray list = new JSONArray();
                for (DqAuthAPPPageBean bean: dqAuthAPPDevs.getPage()) {
                    JSONObject jsonBean = new JSONObject();
                    jsonBean.put("devSn", bean.getDevSn());
                    jsonBean.put("devCode", bean.getDevCode());
                    jsonBean.put("isOwer", bean.getIsOwer());
                    jsonBean.put("userId", bean.getUserId());
                    list.add(jsonBean);
                }
                data.put("list", list);
                onSuccess(null, data, jsCallback);
            }

            @Override
            public void dqAuthDevsOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * 点击设备选择设备
     * @param position 列表序号
     */
    @JSMethod(uiThread = true)
    public void dqGetDevInfo(int position) {
        ApiButtUtils.dqGetDevInfo(position);
    }

    /**
     * 发送指令
     * @param com
     */
    @JSMethod(uiThread = true)
    public void sendCom(String com) {
        ApiButtUtils.sendCom(com);
    }

    /**
     * 绑定设备
     * @param devSn
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqBindDevice(String devSn, final JSCallback jsCallback) {
        ApiButtUtils.dqBindDevice(devSn, new DqBindDeviceCallBack() {
            @Override
            public void dqBindDeviceSuccess(String s) {
                if (jsCallback == null) return;
                onSuccess(s, null, jsCallback);
            }

            @Override
            public void dqBindDeviceOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * 获取位置信息
     * @param params
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqDeviceGps(JSONObject params, final JSCallback jsCallback) {
        String devCode = params.getString("devCode");
        long startTime = params.getLongValue("startTime");
        long endTime = params.getLongValue("endTime");
        int pageIndex = params.getIntValue("pageIndex");
        int pageSize = params.getIntValue("pageSize");
        ApiButtUtils.dqDeviceGps(
                devCode,
                startTime,
                endTime,
                pageIndex,
                pageSize,
                new DqDeviceGpsCallBack() {
                    @Override
                    public void dqDeviceGpsSuccess(DqGpsInfo dqGpsInfo) {
                        if (jsCallback == null) return;
                        JSONObject data = new JSONObject();
                        data.put("devCode", dqGpsInfo.getDevCode());
                        data.put("userId", dqGpsInfo.getUserId());
                        data.put("currTime", dqGpsInfo.getCurrTime());
                        data.put("longitude", dqGpsInfo.getLongitude());
                        data.put("latitude", dqGpsInfo.getLatitude());
                        data.put("height", dqGpsInfo.getHeight());
                        data.put("gpsSpeed", dqGpsInfo.getGpsSpeed());
                        data.put("vehSpeed", dqGpsInfo.getVehSpeed());
                        data.put("direction", dqGpsInfo.getDirection());
                        data.put("satelliteNum", dqGpsInfo.getSatelliteNum());
                        data.put("locationEffective", dqGpsInfo.getLocationEffective());
                        data.put("mnc", dqGpsInfo.getMnc());
                        data.put("mcc", dqGpsInfo.getMcc());
                        data.put("lac", dqGpsInfo.getLac());
                        data.put("cid", dqGpsInfo.getCid());
                        data.put("sig", dqGpsInfo.getSig());
                        data.put("receiveTime", dqGpsInfo.getReceiveTime());
                        data.put("eulerX", dqGpsInfo.getEulerX());
                        data.put("eulerY", dqGpsInfo.getEulerY());
                        data.put("eulerZ", dqGpsInfo.getEulerZ());
                        data.put("vehState", dqGpsInfo.getVehState());
                        data.put("vehEvent", dqGpsInfo.getVehEvent());
                        data.put("vehVolt", dqGpsInfo.getVehVolt());
                        onSuccess(null, data, jsCallback);
                    }

                    @Override
                    public void dqDeviceGpsOnError(String s) {
                        if (jsCallback == null) return;
                        onFailure(s, jsCallback);

                    }
                }
        );
    }

    /**
     * stateTurnRight
     * @param devCode
     * @param jsCallback
     */
    public void dqVehState(String devCode, final JSCallback jsCallback) {
        ApiButtUtils.dqVehState(devCode, new DqVehStateCallBack() {
            @Override
            public void dqVehStateSuccess(DqVehState dqVehState) {
                if (jsCallback == null) return;
                JSONObject data = new JSONObject();
                data.put("timStamp", dqVehState.getTimStamp());
                data.put("devCode", dqVehState.getDevCode());
                data.put("time", dqVehState.getTime());
                data.put("unionId", dqVehState.getUnionId());
                data.put("stateTurnLeft", dqVehState.getStateTurnLeft());
                data.put("stateACC", dqVehState.getStateACC());
                data.put("stateRetain1", dqVehState.getStateRetain1());
                data.put("gsmSig", dqVehState.getGsmSig());
                data.put("gsmMcc", dqVehState.getGsmMcc());
                data.put("stateIsBrake", dqVehState.getStateIsBrake());
                data.put("stateHoodOpen", dqVehState.getStateHoodOpen());
                data.put("stateGearP", dqVehState.getStateGearP());
                data.put("stateBootOpen", dqVehState.getStateBootOpen());
                data.put("stateGearN", dqVehState.getStateGearN());
                data.put("stateGearD", dqVehState.getStateGearD());
                data.put("stateGearR", dqVehState.getStateGearR());
                data.put("stateRetain2", dqVehState.getStateRetain2());
                data.put("stateRetain3", dqVehState.getStateRetain3());
                data.put("gsmMnc", dqVehState.getGsmMnc());
                data.put("gsmLac", dqVehState.getGsmLac());
                data.put("gsmCid", dqVehState.getGsmCid());
                data.put("stateIsAutoOFF", dqVehState.getStateIsAutoOFF());
                data.put("stateIsEngineIdling", dqVehState.getStateIsEngineIdling());
                data.put("stateIsDoorLock", dqVehState.getStateIsDoorLock());
                data.put("stateIsPowerOn", dqVehState.getStateIsPowerOn());
                data.put("stateFrontLeftDoorOpen", dqVehState.getStateFrontLeftDoorOpen());
                data.put("stateIsAntiTheftCar", dqVehState.getStateIsAntiTheftCar());
                data.put("stateFrontRightDoorOpen", dqVehState.getStateFrontRightDoorOpen());
                data.put("stateLeftRearDoorOpen", dqVehState.getStateLeftRearDoorOpen());
                data.put("stateIsAntiTheftSystem", dqVehState.getStateIsAntiTheftSystem());
                data.put("stateIsEngineStarted", dqVehState.getStateIsEngineStarted());
                data.put("stateHeadlightOn", dqVehState.getStateHeadlightOn());
                data.put("statePassengerBelt", dqVehState.getStatePassengerBelt());
                data.put("stateBluetoothHeartbeat", dqVehState.getStateBluetoothHeartbeat());
                data.put("stateRightRearDoorOpen", dqVehState.getStateRightRearDoorOpen());
                data.put("stateAirConditioner", dqVehState.getStateAirConditioner());
                data.put("stateBluetooth", dqVehState.getStateBluetooth());
                data.put("stateFaultLight", dqVehState.getStateFaultLight());
                data.put("stateIsHandbrake", dqVehState.getStateIsHandbrake());
                data.put("stateDriverBelt", dqVehState.getStateDriverBelt());
                data.put("stateTurnRight", dqVehState.getStateTurnRight());
                onSuccess(null, data, jsCallback);
            }

            @Override
            public void dqVehStateOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * closeConnect(
     * @param params
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqAuthAssistantKey(JSONObject params, final JSCallback jsCallback) {
        String devCode = params.getString("devCode");
        String uid2 = params.getString("uid2");
        int power = params.getIntValue("power");
        long startTime = params.getLongValue("startTime");
        long endTime = params.getLongValue("endTime");
        ApiButtUtils.dqAuthAssistantKey(devCode, uid2, power, startTime, endTime, new DqAuthAssistantKeyCallBack() {
            @Override
            public void dqAuthAssistantKeyCodeSuccess(String s) {
                if (jsCallback == null) return;
                onSuccess(s, null, jsCallback);
            }

            @Override
            public void dqAuthAssistantKeyOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * 特殊情况想关闭蓝牙
     */
    @JSMethod(uiThread = false)
    public void closeConnect() {
        ApiButtUtils.closeConnect();
    }

    /**
     * 获取授权列表
     * @param params
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqAuthKeys(JSONObject params, final JSCallback jsCallback) {
        String pageIndex = params.getString("pageIndex");
        String pageSize = params.getString("pageSize");
        ApiButtUtils.dqAuthKeys(pageIndex, pageSize, new DqAuthKeysCallBack() {
            @Override
            public void dqAuthKeysSuccess(DqAuthKeys dqAuthKeys) {
                if (jsCallback == null) return;
                JSONObject data = new JSONObject();
                data.put("total", dqAuthKeys.getTotal());
                data.put("pageIndex", dqAuthKeys.getPageIndex());
                data.put("pageSize", dqAuthKeys.getPageSize());
                JSONArray list = new JSONArray();
                for (DqAuthKeysPageBean bean : dqAuthKeys.getPage()) {
                    JSONObject obj = new JSONObject();
                    obj.put("authPower", bean.getAuthPower());
                    obj.put("authData", bean.getAuthData());
                    obj.put("devCode", bean.getDevCode());
                    obj.put("authId", bean.getAuthId());
                    obj.put("authIndex", bean.getAuthIndex());
                    obj.put("toAuthId", bean.getToAuthId());
                    obj.put("senderId", bean.getSenderId());
                    obj.put("senderTime", bean.getSenderId());
                    obj.put("action", bean.getAction());
                    obj.put("pkVal", bean.getPkVal());
                    obj.put("startTime", bean.getStartTime());
                    obj.put("cmd", bean.getCmd());
                    obj.put("endTime", bean.getEndTime());
                    obj.put("id", bean.getId());
                    obj.put("sn", bean.getSn());
                    obj.put("state", bean.getState());
                    obj.put("sourceData", bean.getSourceData());
                    list.add(obj);
                }
                onSuccess(null, data, jsCallback);
            }

            @Override
            public void dqAuthKeysOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * 授权
     * @param params
     */
    @JSMethod(uiThread = false)
    public void dqAuthKeySendData(JSONObject params) {
        int cmd = params.getIntValue("cmd");
        int sn = params.getIntValue("sn");
        String uid = params.getString("uid");
        int action = params.getIntValue("action");
        String devId = params.getString("devId");
        byte[] data = params.getBytes("data");
        int uid_index = params.getIntValue("uid_index");
        DqMcuCommInfo info = new DqMcuCommInfo(cmd, sn, uid, action, devId, data, uid_index);
        ApiButtUtils.dqAuthKeySendData(info);
    }

    /**
     * 撤销授权
     * @param id
     * @param jsCallback
     */
    @JSMethod(uiThread = false)
    public void dqDelAuthKey(String id, final JSCallback jsCallback) {
        ApiButtUtils.dqDelAuthKey(id, new DqDelAuthKeyCallBack() {
            @Override
            public void dqDelAuthKeySuccess(String s) {
                if (jsCallback == null) return;
                onSuccess(s, null, jsCallback);
            }

            @Override
            public void dqDelAuthKeyOnError(String s) {
                if (jsCallback == null) return;
                onFailure(s, jsCallback);
            }
        });
    }

    /**
     * 释放资源
     */
    @JSMethod(uiThread = false)
    public void dqClear() {
        ApiButtUtils.dqClear();
    }
}
